import {defineStore} from 'pinia'
import {ref} from 'vue'
import userAPI from '@/api/user'
import {clearAuth, getToken, getUserInfo, setToken, setUserInfo} from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
    // 状态
    const token = ref(getToken())
    const userInfo = ref(getUserInfo())

    // 登录
    const login = async (phone, password) => {
        try {
            const res = await userAPI.loginWithPhone(phone, password)
            token.value = res.token
            userInfo.value = {
                id: res.id,
                username: res.username,
                phone: res.phone
            }
            // 保存到本地存储
            setToken(res.token)
            setUserInfo(userInfo.value)
            return res
        } catch (error) {
            throw error
        }
    }

    // 登出
    const logout = () => {
        token.value = null
        userInfo.value = null
        clearAuth()
    }

    // 初始化状态
    const initUserState = () => {
        token.value = getToken()
        userInfo.value = getUserInfo()
    }

    return {
        token,
        userInfo,
        login,
        logout,
        initUserState
    }
})